const JWT = require('jsonwebtoken')
const {
    secretKey,
    expiresIn
} = require('../config')

let formate = (v) => {
    let r = {}
    for (let [key, value] of v) {
        r[key] = value
    }
    return r;
}

function generateToken(uid) {
    let token = JWT.sign(uid, secretKey, {
        expiresIn
    })

    return token;
}

function generatePassword(pwd){
    let token = JWT.sign({pwd}, secretKey)

    return token;
}

function verifyToken(token) {
    try {
        const res = JWT.verify(token, secretKey)
        return {tag:1};
    } catch (e) {
        if(e.expiredAt){
            return { tag:2}
        }else{
            return {tag:0};
        }
       
    }
}


function decodePassword(token){
    try {
        return JWT.decode(token, secretKey).pwd;
    } catch (e) {
        return false;
    }
}

function getUserId(token){
    try {
        return JWT.decode(token, secretKey).uid;
    } catch (e) {
        return false;
    }
}

module.exports = {
    formate,
    generateToken,
    verifyToken,
    generatePassword,
    decodePassword,
    getUserId
};